import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:Sayagh/Configs.dart';
import 'package:Sayagh/i18n/i18nLocale.dart';
import 'package:Sayagh/news/Posts.dart';
import 'package:flutter/material.dart';

// import 'package:Sayagh/i18n/i18nLocale.dart';
Future<List> categories({String url}) async {
  if (url == null) url = website + "/wp-json/wp/v2/categories";
  StringBuffer content = new StringBuffer();
  Completer completer = new Completer();
  var client = HttpClient();
  var req = await client.getUrl(Uri.parse(url));
  var res = await req.close();
  var resp = res.transform(Utf8Decoder());
  resp
      .listen((body) => {content.write(body)})
      .onDone(() => completer.complete(content));
  var body = await completer.future;
  List jsson = json.decode(body.toString());
  Map<int,Map> idAsKey = new Map();
  jsson.forEach((cat) {
    idAsKey[cat['id']] = cat;
  });

  Map<String,Map> nameAsKey = new Map();
  jsson.forEach((cat) {
    nameAsKey[cat['name']] = cat;
  });

  return [idAsKey, nameAsKey];
}

void main(List<String> args) {
  categories();
}

class WpCategories extends StatelessWidget {
  final String _url;
  WpCategories(this._url);
  @override
  Widget build(BuildContext context) {
    Future<List> wpCategoriesList;
    wpCategoriesList = categories(url: this._url);
    return Scaffold(body: FutureBuilder(
      future:wpCategoriesList ,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data == null) {
          return Card(
            child: Text(
              i18nLocale[ourLocale]['reciving'],
              textDirection: TextDirection.rtl,
              textAlign: TextAlign.center,
            ),
          );
        }
        Map<int,Map> byId = snapshot.data[0];
        List<Card> gridTiles = [];
         byId.forEach((int key, Map value){
           gridTiles.add(Card(child: ListTile(
            title: Text(
              value['name'],
              textDirection: TextDirection.rtl,),
            onTap: ()=> Navigator.push(context,
                MaterialPageRoute(builder: (context) => WpPosts("$website/wp-json/wp/v2/posts",key))),
          ),
          ),);
        });
        return ListView(
        children:gridTiles,
        );
        
      },
    ),
    appBar: AppBar( title:asnafHeader,centerTitle: false,),
    );
  }
}
